from werkzeug.security import generate_password_hash, check_password_hash

from applications.extensions import db
import datetime
class User(db.Model):
    __tablename__ = 'user'
    __table_args__ = {
        'mysql_engine': 'InnoDB',
        'mysql_charset': 'utf8mb4',
        'mysql_collate': 'utf8mb4_unicode_ci'
    }

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(50), comment='用户名')
    password = db.Column(db.String(128), nullable=True, comment='密码')
    email = db.Column(db.String(150), nullable=True, comment='Email')
    mobile = db.Column(db.String(15), nullable=True, comment='手机')
    idcard = db.Column(db.String(18), nullable=True, comment='身份证号')
    cardid = db.Column(db.String(20), nullable=True, comment='卡号')
    usertype = db.Column(db.Integer, nullable=False, default=0, comment='1学生2老师3职员4家长')
    signyear = db.Column(db.CHAR(4), nullable=True, comment='合同签订年（入学时间）')
    signmonth = db.Column(db.String(2), nullable=True, comment='合同签订月（入学时间）')
    signlenth = db.Column(db.Integer, nullable=True, comment='合同期限、年')
    basedn = db.Column(db.String(120), nullable=True, comment='Base DN')
    truename = db.Column(db.String(50), nullable=True, comment='真实姓名')
    py = db.Column(db.String(20), nullable=True, comment='拼音')
    pinyin = db.Column(db.String(50), nullable=True, comment='拼音')
    sysuid = db.Column(db.String(50), nullable=True, comment='第三方uid')
    campus = db.Column(db.String(20), nullable=True, comment='1初中2高中3国际4亦庄')
    depart = db.Column(db.String(100), nullable=True, comment='部门')
    readval = db.Column(db.Integer, nullable=False, default=0, comment='阅读权限')
    cid = db.Column(db.Integer, nullable=False, default=0, comment='分类ID')
    group = db.Column(db.Integer, nullable=False, default=0, comment='默认组')
    regip = db.Column(db.String(15), nullable=False, default='0', comment='注册IP')
    loginip = db.Column(db.String(15), nullable=False, default='0', comment='最后一次登录IP')
    binduid = db.Column(db.String(15), nullable=False, default='0', comment='绑定账户')
    status = db.Column(db.Integer, nullable=False, default=0, comment='0未激活 1激活合同内 2合同外 -1删除 -2锁定')
    hash = db.Column(db.String(32), nullable=True, comment='掩码')
    rkey = db.Column(db.String(32), nullable=True, comment='唯一识别码')
    avatar = db.Column(db.String(255), nullable=True, comment='头像')
    timeout = db.Column(db.Integer, nullable=True, comment='过期时间')
    utime = db.Column(db.Integer, nullable=True, comment='更新时间', default=datetime.datetime.now, onupdate=datetime.datetime.now)
    ctime = db.Column(db.DateTime, default=datetime.datetime.now, nullable=False, comment='创建时间')

    def __repr__(self):
        return f'<User {self.username}>'

    def set_password(self, password):
        self.password = generate_password_hash(password)

    def validate_password(self, password):
        return check_password_hash(self.password, password)
